from plugins.template import ParserTemplate
import re

def get_parsers():
	return {"Ziggy" : Parser}

class Parser(ParserTemplate):
	"""
	Grammar:
	Page = Number NL .
	Panel = ":p" Number ":" NL .
	Text = Translation { // Translation } NL.

	>>> from io import StringIO
	>>> text = '''162
	... :p1:
	... Deep below Sunpu Castle... // では夜な夜な人の lies a hidden chamber known only to a select few.
	... Night after night, horrific cries emerge from the chamber - cries that could scarcely come from human lips.
	...
	... :p2:
	... Aaagh!
	...
	... 163
	... :p1:
	... Let me... // tell you of inscriptions // では夜な夜な人の test3.
	... '''
	>>> parser = Parser(StringIO(text))
	>>> parser.next_token()
	Token(page='162', panel='1', text='Deep below Sunpu Castle...', line=2)
	>>> parser.next_token()
	Token(page='162', panel='1', text='lies a hidden chamber known only to a select few.', line=2)
	>>> parser.next_token()
	Token(page='162', panel='1', text='Night after night, horrific cries emerge from the chamber - cries that could scarcely come from human lips.', line=3)
	>>> parser.next_token()
	Token(page='162', panel='2', text='Aaagh!', line=6)
	>>> parser.next_token()
	Token(page='163', panel='1', text='Let me...', line=10)
	>>> parser.next_token()
	Token(page='163', panel='1', text='tell you of inscriptions', line=10)
	>>> parser.next_token()
	Token(page='163', panel='1', text='test3.', line=10)
	>>> parser.next_token()
	"""
	_PageRe = re.compile('''(\d+)	# simple number as group
	$ # end''', re.VERBOSE | re.IGNORECASE)
	
	_PanelRe = re.compile(''':p  # :p
	(\d+) # panel number
	:$  # closing : ''', re.VERBOSE | re.IGNORECASE)
	
	def __init__(self, file):
		# used in case we have more than one token on each line
		self._next_tokens = []
		super().__init__(file)
	
	def _parse_next(self, last_token):
		try:
			page = self._parse_re(Parser._PageRe) or last_token.page
			panel = self._parse_re(Parser._PanelRe) or last_token.panel
			line = self._cur_line
			texts = self._parse_text()
			return [self.Token(page, panel, text, line) for text in texts]
		except self.ParserEndError:
			return [None]
	
	def _parse_text(self):
		# first remove everything between [] then remove japanese characters
		texts = [self._remove_japanese_chars(re.sub(r"\[.*\]", "", s.strip())) for s in self._get_line().split("//")]
		self._next_line()
		return texts

if __name__ == '__main__':
	import doctest
	doctest.testmod()
